<?php
/**
 * 还康科技活动报名
 *
 * @author 指尖营销
 * @url http://bbs.we7.cc/
 */
defined('IN_IA') or exit('Access Denied');
require IA_ROOT.'/addons/zh_hkad/inc/func/core.php';
class Zh_hkadModuleSite extends Core {
     public function doMobileIndex(){
        global $_W, $_GPC;
        load()->func('tpl');
        //$list=pdo_fetchall("SELECT * FROM `zh_hkad_active` WHERE uniacid=".$_W['uniacid']." AND state=1 ORDER BY sort DESC");
        $list=pdo_fetchall(" select * from" .tablename('zh_hkad_active') . "where uniacid={$_W['uniacid']} and state=1 order by sort desc");
        for($j=0;$j<count($list);$j++){
              $list[$j]['imgs']=explode(",",$list[$j]['imgs']);
              $list[$j]['img']=$list[$j]['imgs'][0];
        }
        include $this->template('index');
    }

    public function doMobileRegist(){
        global $_W, $_GPC;
        load()->func('tpl');
        $rinfo=pdo_get('zh_hkad_active',array('id'=>$_GPC['id']));
        include $this->template('regist');
    }

    public function doMobileBaoming(){
        global $_W, $_GPC;
        load()->func('tpl');
        $list=pdo_fetchall(" select * from" .tablename('zh_hkad_register') . "where l_id={$_GPC['id']} and state=1 order by create_time desc");
        $peoples=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('zh_hkad_register')." WHERE l_id=".$_GPC['id']." AND l_id=".$_GPC['id']." AND state=1 ORDER BY id DESC ");
        include $this->template('baoming');
    }
    public function doMobileDetail(){
     global $_W, $_GPC;
     load()->func('tpl');
     $active=pdo_get('zh_hkad_active',array('id'=>$_GPC['id']));
     $active['imgs']=explode(",",$active['imgs']);
     $active['stoptimesjc']=strtotime($active['stoptime']);
     $lnglats=explode(',', $active['latlng']);
     $lnglatarr[0]=$lnglats[1];
     $lnglatarr[1]=$lnglats[0];
     $lnglat=implode(',', $lnglatarr);
     $peoples=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('zh_hkad_register')." WHERE uniacid=".$_W['uniacid']." AND l_id=".$_GPC['id']." AND state=1 ORDER BY id DESC ");
     $now=time();
     $lpeople=$active['people']-$peoples;
     $is=pdo_get('zh_hkad_register',array('openid'=>$_W['fans']['openid'],'l_id'=>$_GPC['id']));
     include $this->template('detail');
    }
     public function doMobileOrders(){
        global $_W, $_GPC;
        load()->func('tpl');
        /*if($_GPC['openid']){
            $list=pdo_fetchall("SELECT a.*,b.title,b.imgs,b.address,b.people,b.money,b.start,b.end,b.stoptime FROM ".tablename('zh_hkad_register'). " a left join " . tablename("zh_hkad_active") . " b on a.l_id=b.id WHERE a.uniacid=:uniacid and a.openid=:openid ORDER BY b.time desc", array(':uniacid'=>$_W['uniacid'],':openid'=>$_GPC['openid']));
        }else{*/
          $list=pdo_fetchall("SELECT a.*,b.title,b.imgs,b.address,b.people,b.money,b.start,b.end,b.stoptime FROM ".tablename('zh_hkad_register'). " a left join " . tablename("zh_hkad_active") . " b on a.l_id=b.id WHERE a.uniacid=:uniacid and a.openid=:openid ORDER BY b.time desc", array(':uniacid'=>$_W['uniacid'],':openid'=>$_W['fans']['openid']));
        /*}*/
        
        for($j=0;$j<count($list);$j++){
              $list[$j]['imgs']=explode(",",$list[$j]['imgs']);
              $list[$j]['img']=$list[$j]['imgs'][0];
        }
        
        $list1=pdo_fetchall("SELECT a.*,b.title,b.imgs,b.address,b.people,b.money,b.start,b.end,b.stoptime FROM ".tablename('zh_hkad_register'). " a left join " . tablename("zh_hkad_active") . " b on a.l_id=b.id WHERE a.state=1 and a.uniacid=:uniacid and a.openid=:openid ORDER BY b.time desc", array(':uniacid'=>$_W['uniacid'],':openid'=>$_W['fans']['openid']));
        for($j=0;$j<count($list1);$j++){
              $list1[$j]['imgs']=explode(",",$list1[$j]['imgs']);
              $list1[$j]['img']=$list1[$j]['imgs'][0];
        }
        
        $list2=pdo_fetchall("SELECT a.*,b.title,b.imgs,b.address,b.people,b.money,b.start,b.end,b.stoptime FROM ".tablename('zh_hkad_register'). " a left join " . tablename("zh_hkad_active") . " b on a.l_id=b.id WHERE a.state=2 and a.uniacid=:uniacid and a.openid=:openid ORDER BY b.time desc", array(':uniacid'=>$_W['uniacid'],':openid'=>$_W['fans']['openid']));
        for($j=0;$j<count($list2);$j++){
              $list2[$j]['imgs']=explode(",",$list2[$j]['imgs']);
              $list2[$j]['img']=$list2[$j]['imgs'][0];
        }
        include $this->template('orders');
    }
    //注册信息
    public function doMobileRegister(){
        global $_W, $_GPC;
        $data['openid']=$_W['fans']['openid'];
        $data['name'] = $_GPC['name'];
        $data['phone'] = $_GPC['phone'];
        $data['work'] = $_GPC['work'];
        $data['l_id'] = $_GPC['id'];
        $data['state'] = 2;
        $data['detail_address'] = $_GPC['detail_address'];
        $data['create_time'] = date('Y-m-d H:i:s',time());
        $data['uniacid']=$_W['uniacid'];
        $exist=pdo_get('zh_hkad_register',array('openid'=>$_W['fans']['openid'],'l_id'=>$_GPC['id'],'uniacid'=>$_W['uniacid']));
        if (empty($exist)) {
            $res=pdo_insert('zh_hkad_register',$data);
            $data_id=pdo_insertid();
            if($res){   
                $active=pdo_get('zh_hkad_active',array('id'=>$_GPC['id']));
                $_GPC['money']=$active['money'];
                $tid=$data_id.date('Ymdhis',time());
                $ordernum = array(
                        'ordernum' => $tid,
                );
                pdo_update('zh_hkad_register',$ordernum,array('id'=>$data_id));
                $orderid=date('Ymdhis',time());
                $fee = floatval($_GPC['money']);
                if($fee <= 0) {
                    message('支付错误, 金额小于0');
                }
                $params = array(
                    'tid' => $tid,      //充值模块中的订单号，此号码用于业务模块中区分订单，交易的识别码
                    'ordersn' => $orderid,  //收银台中显示的订单号
                    'title' => '活动报名费',          //收银台中显示的标题
                    'fee' => $fee,//收银台中显示需要支付的金额,只能大于 0
                    'user' => $_GPC['name'],
                );
                $paydata=$this->pay($params);
                if (is_error($paydata)) {
                    $this->result($paydata['errno'], $paydata['message']);
                }
                $payresult=$this->result(0, '', $paydata);
                $this->tmdpayResult($payresult);
                //echo json_encode(array('msg'=>'提交成功','code'=>'200','data_id'=>$data_id),320);exit();
            }else{
                echo json_encode(array('msg'=>'提交失败','code'=>'501'),320);exit();
            }
        }else{
            if ($exist['state']==2) {
                $active=pdo_get('zh_hkad_active',array('id'=>$_GPC['id']));
                $_GPC['money']=$active['money'];
                $tid=$exist['id'].date('Ymdhis',time());
                $ordernum = array(
                        'ordernum' => $tid,
                );
                pdo_update('zh_hkad_register',$ordernum,array('id'=>$exist['id']));
                $orderid=date('Ymdhis',time());
                $fee = floatval($_GPC['money']);
                if($fee <= 0) {
                    message('支付错误, 金额小于0');
                }
                $params = array(
                    'tid' => $tid,      //充值模块中的订单号，此号码用于业务模块中区分订单，交易的识别码
                    'ordersn' => $orderid,  //收银台中显示的订单号
                    'title' => '活动报名费',          //收银台中显示的标题
                    'fee' => $fee,//收银台中显示需要支付的金额,只能大于 0
                    'user' => $_GPC['name'],
                );
                $paydata=$this->pay($params);
                if (is_error($paydata)) {
                    $this->result($paydata['errno'], $paydata['message']);
                }
                $payresult=$this->result(0, '', $paydata);
                $this->tmdpayResult($payresult);
            }elseif ($exist['state']==1) {
                echo json_encode(array('msg'=>'该用户已报名成功！！','code'=>'502'),320);exit();
            }
        }
    }

    public function tmdpayResult($payresult) {
        global $_GPC;
        global $_W;
        var_dump($payresult);die;
        $orderid = $_GPC['tid'];
        $order_type = trim($_GPC['order_type']);
        //订单id
        $paylog = pdo_get('zh_hkad_register', array('uniacid' => $_W['uniacid'], 'module' => 'zh_hkad', 'tid' => $orderid));
        $state = intval($paylog['state']) === 1;
        $this->result($state, $state ? '支付成功' : '支付失败');
    }
    public function doMobileDdpay(){
        global $_W, $_GPC;
        $reg=pdo_get('zh_hkad_register',array('openid'=>$_W['fans']['openid'],'id'=>$_GPC['id'],'uniacid'=>$_W['uniacid']));
        $active=pdo_get('zh_hkad_active',array('id'=>$reg['l_id'],'uniacid'=>$_W['uniacid']));
        //$tid=$_GPC['id'].date('Ymdhis',time());
        $orderid=date('Ymdhis',time());
        $fee = floatval($active['money']);
        if($fee <= 0) {
            message('支付错误, 金额小于0');
        }
        $params = array(
            'tid' => $reg['ordernum'],      //充值模块中的订单号，此号码用于业务模块中区分订单，交易的识别码
            'ordersn' => $orderid,  //收银台中显示的订单号
            'title' => '活动报名费',          //收银台中显示的标题
            'fee' => $fee,//收银台中显示需要支付的金额,只能大于 0
            'user' => $_GPC['name'],
        );
        $this->pay($params);
    }
    public function doMobileRpay(){
        global $_W, $_GPC;
        $active=pdo_get('zh_hkad_active',array('uniacid'=>$_W['uniacid']));
        $_GPC['money']=$active['money'];
        $openid=pdo_get('zh_hkad_register',array('openid'=>$_W['fans']['openid'],'uniacid'=>$_W['uniacid']));
        $username=pdo_get('zh_hkad_register',array('id'=>$openid['id'],'uniacid'=>$_W['uniacid']),'name');
        $tid=$openid['id'].date('Ymdhis',time());
        $orderid=date('Ymdhis',time());
        $fee = floatval($_GPC['money']);
        if($fee <= 0) {
            message('支付错误, 金额小于0');
        }
        // 一些业务代码。
        //构造支付请求中的参数
        $params = array(
            'tid' => $tid,      //充值模块中的订单号，此号码用于业务模块中区分订单，交易的识别码
            'ordersn' => $orderid,  //收银台中显示的订单号
            'title' => '报名费',          //收银台中显示的标题
            //'fee' => $chargerecord['fee'],      //收银台中显示需要支付的金额,只能大于 0
            'fee' => $fee,
            //'user' => $_W['member']['uid'],     //付款用户, 付款的用户名(选填项)
            'user' => $username['name'],
        );
        // var_dump($params);die;
        //调用pay方法
        $this->pay($params);
    }
    
    public function payResult($params) {
        global $_W, $_GPC;
        //一些业务代码
        $gordernums=pdo_getall('zh_hkad_register',array('uniacid'=>$_W['uniacid']));
        $ok=0;
        foreach ($gordernums as $value) {
            if (in_array($params['tid'], $value)){
                $ok=1;
            }
        }
        if ($ok==1) {
            //根据参数params中的result来判断支付是否成功
            if ($params['result'] == 'success' && $params['from'] == 'notify') {
                
            }
            //因为支付完成通知有两种方式 notify，return,notify为后台通知,return为前台通知，需要给用户展示提示信息
            //return做为通知是不稳定的，用户很可能直接关闭页面，所以状态变更以notify为准
            //如果消息是用户直接返回（非通知），则提示一个付款成功
            //如果是JS版的支付此处的跳转则没有意义
            if ($params['from'] == 'return') {
                if ($params['result'] == 'success') {
                    $user_data = array(
                        'state' => 1,
                    );
                    pdo_update('zh_hkad_register',$user_data,array('openid'=>$_W['fans']['openid'],'ordernum'=>$params['tid'],'uniacid'=>$_W['uniacid']));
                    $ropenid=pdo_get('zh_hkad_register',array('openid'=>$_W['fans']['openid'],'ordernum'=>$params['tid'],'uniacid'=>$_W['uniacid']));
                    message('支付成功！', $this->createMobileUrl('detail',array('id'=>$ropenid['l_id'])), 'success');
                } else {
                    message('支付失败！', $this->createMobileUrl('regist'), 'error');
                }
            }
        }
        
    }
    //报名上传图片
    public function doMobileUploads(){
        global $_W, $_GPC;
        $destination_folder="../attachment/hkad/";
        if(!file_exists($destination_folder)) //如果文件(夹)不存在
        {
            mkdir($destination_folder,0777); //创建对应文件(夹),并设置权限为全部可读可写可操作
        }
        chmod($destination_folder , 0777);
        move_uploaded_file($_FILES['upload_file']['tmp_name'], $destination_folder.$_FILES['upload_file']['name']);
    }
    //头像上传图片
    public function doMobileUploadhead(){
        global $_W, $_GPC;
        // var_dump($_GPC);
        // var_dump(111);
        // var_dump($_FILES);
        // exit;
        $destination_folder="../attachment/hkad/";
        if(!file_exists($destination_folder)) //如果文件(夹)不存在
        {
            mkdir($destination_folder,0777); //创建对应文件(夹),并设置权限为全部可读可写可操作
        }
        chmod($destination_folder , 0777);
        move_uploaded_file($_FILES['img']['tmp_name'], $destination_folder.$_FILES['img']['name']);
    }
    public function doMobileUpload(){
        global $_W, $_GPC;
        $uptypes=array(  
            'image/jpg',  
            'image/jpeg',  
            'image/png',  
            'image/pjpeg',  
            'image/gif',  
            'image/bmp',  
            'image/x-png'  
            );  
        $max_file_size=2000000;     //上传文件大小限制, 单位BYTE  
        //   $destination_folder="../attachment/zh_tcwq/".$_W['uniacid']."/".date(Y)."/".date(m)."/".date(d)."/"; //上传文件路径  
        $destination_folder="../attachment/"; //上传文件路径  
        $watermark=2;      //是否附加水印(1为加水印,其他为不加水印);  
        $watertype=1;      //水印类型(1为文字,2为图片)  
        $waterposition=1;     //水印位置(1为左下角,2为右下角,3为左上角,4为右上角,5为居中);  
        $waterstring="666666";  //水印字符串  
        // $waterimg="xplore.gif";    //水印图片  
        $imgpreview=1;      //是否生成预览图(1为生成,其他为不生成);  
        $imgpreviewsize=1/2;    //缩略图比例 
        if (!is_uploaded_file($_FILES["upfile"]['tmp_name']))  
        //是否存在文件  
        {  
            echo "图片不存在!";  
            exit;  
        }
        $file = $_FILES["upfile"];
        if($max_file_size < $file["size"])
        //检查文件大小  
        {
            echo "文件太大!";
            exit;
        }
        if(!in_array($file["type"], $uptypes))  
        //检查文件类型
        {
            echo "文件类型不符!".$file["type"];
            exit;
        }
        if(!file_exists($destination_folder))
        {
            mkdir($destination_folder);
        }  
        $filename=$file["tmp_name"];  
        $image_size = getimagesize($filename);  
        $pinfo=pathinfo($file["name"]);  
        $ftype=$pinfo['extension'];  
        $destination = $destination_folder.str_shuffle(time().rand(111111,999999)).".".$ftype;  
        if (file_exists($destination) && $overwrite != true)  
        {  
            echo "同名文件已经存在了";  
            exit;  
        }  
        if(!move_uploaded_file ($filename, $destination))  
        {  
            echo "移动文件出错";  
            exit;
        }
        $pinfo=pathinfo($destination);  
        $fname=$pinfo['basename'];  
        // echo " <font color=red>已经成功上传</font><br>文件名:  <font color=blue>".$destination_folder.$fname."</font><br>";  
        // echo " 宽度:".$image_size[0];  
        // echo " 长度:".$image_size[1];  
        // echo "<br> 大小:".$file["size"]." bytes";  
        if($watermark==1)  
        {  
            $iinfo=getimagesize($destination,$iinfo);  
            $nimage=imagecreatetruecolor($image_size[0],$image_size[1]);
            $white=imagecolorallocate($nimage,255,255,255);
            $black=imagecolorallocate($nimage,0,0,0);
            $red=imagecolorallocate($nimage,255,0,0);
            imagefill($nimage,0,0,$white);
            switch ($iinfo[2])
            {  
                case 1:
                $simage =imagecreatefromgif($destination);
                break;
                case 2:
                $simage =imagecreatefromjpeg($destination);
                break;
                case 3:
                $simage =imagecreatefrompng($destination);
                break;
                case 6:
                $simage =imagecreatefromwbmp($destination);
                break;
                default:
                die("不支持的文件类型");
                exit;
            }
            imagecopy($nimage,$simage,0,0,0,0,$image_size[0],$image_size[1]);
            imagefilledrectangle($nimage,1,$image_size[1]-15,80,$image_size[1],$white);
            switch($watertype)  
            {
                case 1:   //加水印字符串
                imagestring($nimage,2,3,$image_size[1]-15,$waterstring,$black);
                break;
                case 2:   //加水印图片
                $simage1 =imagecreatefromgif("xplore.gif");
                imagecopy($nimage,$simage1,0,0,0,0,85,15);
                imagedestroy($simage1);
                break;
            }
            switch ($iinfo[2])
            {
                case 1:
                //imagegif($nimage, $destination);
                imagejpeg($nimage, $destination);
                break;
                case 2:
                imagejpeg($nimage, $destination);
                break;
                case 3:
                imagepng($nimage, $destination);
                break;
                case 6:
                imagewbmp($nimage, $destination);
                //imagejpeg($nimage, $destination);
                break;
            }
            //覆盖原上传文件
            imagedestroy($nimage);
            imagedestroy($simage);
        }
        // if($imgpreview==1)  
        // {  
        // echo "<br>图片预览:<br>";  
        // echo "<img src=\"".$destination."\" width=".($image_size[0]*$imgpreviewsize)." height=".($image_size[1]*$imgpreviewsize);  
        // echo " alt=\"图片预览:\r文件名:".$destination."\r上传时间:\">";  
        // } 
        echo $fname;
        @require_once (IA_ROOT . '/framework/function/file.func.php');
        @$filename=$fname;
        @file_remote_upload($filename); 
    }
    private function getaccess_token($_W){
                $res=pdo_get('zh_hkad_system',array('uniacid'=>$_W['uniacid']));
                $appid=$res['appid'];
                $secret=$res['appsecret'];
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret."";
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL,$url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
                $data = curl_exec($ch);
                curl_close($ch);
                $data = json_decode($data,true);
                return $data['access_token'];
    }
    public function doMobileShare(){
        global $_W, $_GPC;
      
        $access_token = $this->getaccess_token($_W);
        
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
        $data = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($data,true);
        $system=pdo_get('zh_hkad_system',array('uniacid'=>$_W['uniacid']));
        $parameters = array(
            'appId' => $system['appid'], //小程序ID
            'timeStamp' => time(), //时间戳
            'nonceStr' => $this->createNoncestr(), //随机串
            //'signType' => 'MD5'//签名方式
        );
        //签名
        //$parameters['signature'] = $this->getSign($parameters);
        $parameters['signature'] =sha1("jsapi_ticket=".$data['ticket']."&noncestr=".$parameters['nonceStr']."&timestamp=".$parameters['timeStamp']."&url=".$_W['siteroot']."app/index.php?i=".$_W['uniacid']."&c=entry&do=detail&m=zh_hkad&id=".$_GPC['id']);
        echo json_encode($parameters);exit();
    
    }
    
    public function doMobileShareindex(){
        global $_W, $_GPC;
      
        $access_token = $this->getaccess_token($_W);
        
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
        $data = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($data,true);
        $system=pdo_get('zh_hkad_system',array('uniacid'=>$_W['uniacid']));
        $parameters = array(
            'appId' => $system['appid'], //小程序ID
            'timeStamp' => time(), //时间戳
            'nonceStr' => $this->createNoncestr(), //随机串
            //'signType' => 'MD5'//签名方式
        );
        //签名
        //$parameters['signature'] = $this->getSign($parameters);
        $parameters['signature'] =sha1("jsapi_ticket=".$data['ticket']."&noncestr=".$parameters['nonceStr']."&timestamp=".$parameters['timeStamp']."&url=".$_W['siteroot']."app/index.php?i=".$_W['uniacid']."&c=entry&do=index&m=zh_hkad");
        echo json_encode($parameters);exit();
    
    }
    public function doMobileTiaos(){
        global $_W, $_GPC;
        $active=pdo_get('zh_hkad_active',array('id'=>$_GPC['id']));
        echo $active['content'];exit();
    }
    
    //作用：产生随机字符串，不长于32位
    private function createNoncestr($length = 32) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }


    //作用：生成签名
    private function getSign($Obj) {
        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //签名步骤二：在string后加入KEY
        $String = $String . "&key=" . $this->key;
        //签名步骤三：MD5加密
        $String = md5($String);
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        return $result_;
    }


    ///作用：格式化参数，签名过程需要使用
    private function formatBizQueryParaMap($paraMap, $urlencode) {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar;
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }
}